<?php

include "../lib/start.php";

check_session();
check_permission(ADM_PERM);

$sel_alunni = "SELECT id_alunno, classe, id_classe FROM alunni";
try{
	$res_alunni = $db->executeQuery($sel_alunni);
} catch (MySQLException $ex){
	print "ko#".$ex->getQuery()."#".$ex->getMessage();
	exit;
}

$sel_anno = "SELECT * FROM anni ORDER BY id_anno DESC LIMIT 1";
$res_anno = $db->executeQuery($sel_anno);
$year = new AnnoScolastico($res_anno->fetch_assoc());
$anno = $year->get_ID();
$quadrimestre = 1;
if(date("Ymd") > format_date($year->get_fine_quadrimestre(), IT_DATE_STYLE, SQL_DATE_STYLE, ""))
	$quadrimestre = 2;

$sel_materie = "SELECT id_materia FROM materie WHERE pagella = 1 ORDER BY id_materia";
$res_materie = $db->executeQuery($sel_materie);
$materie = array();
while($materia = $res_materie->fetch_assoc()){
	array_push($materie, $materia['id_materia']);
}

while($alunno = $res_alunni->fetch_assoc()){
	$id_alunno = $alunno['id_alunno'];
	$classe = $alunno['id_classe'];
	foreach($materie as $materia){
		$ins = "INSERT INTO scrutini (alunno, classe, anno, quadrimestre, materia) VALUES ($id_alunno, $classe, $anno, $quadrimestre, $materia)";
		try{
			$r_ins = $db->executeUpdate($ins);
		} catch (MySQLException $ex){
        	print "ko#".$ex->getQuery()."#".$ex->getMessage();
			exit;
        }
	}
}

print "ok;";
exit;

?>